package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleCollectionMapper;
import com.heima.article.service.ApArticleCollectionBehaviorService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.behavior.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Slf4j
@Transactional
public class ApArticleCollectionBehaviorServiceImpl extends ServiceImpl<ApArticleCollectionMapper, ApCollection> implements ApArticleCollectionBehaviorService {
    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult collectBehavior(CollectionBehaviorDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        String key = BehaviorConstants.ARTICLE_COLLECTION_BEHAVIOR + user.getId();
        if (dto.getOperation() == 0) {
            Object obj = cacheService.hGet(key, dto.getEntryId().toString());
            if (obj != null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已收藏该文章");
            }
            log.info("保存当前key:{},{}", key, dto.getEntryId().toString());
            cacheService.hPut(key, dto.getEntryId().toString(), JSON.toJSONString(dto));
        } else {
            log.info("删除当前key:{},{}", key, dto.getEntryId().toString());
            cacheService.hDelete(key, dto.getEntryId().toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
